package code.example.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

public class ZookeeperHolder {
    volatile  ZooKeeper zooKeeper = null;
    private static Logger logger = LoggerFactory.getLogger(ZookeeperHolder.class);
    WatcherDefault watcherDefault = new WatcherDefault();
    AtomicBoolean connecting = new  AtomicBoolean(false);
    public ZooKeeper getInstance() throws Exception {
        if(zooKeeper == null){
            if(connecting.compareAndSet(false,true)){
                ZooKeeper zooKeeper = new ZooKeeper(ZkConstant.connectString,
                        ZkConstant.sessionTimeout,
                        watcherDefault);
                watcherDefault.await();
                this.zooKeeper = zooKeeper;
            }else{
                watcherDefault.await();
            }
        }
        return zooKeeper;
    }
    public Stat exists(String path) throws Exception {
       return  getInstance().exists(path,null);
    }
    public void create(String path) throws  Exception {
        getInstance().create(path,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }
    public void create(String path,String data) throws  Exception {
        getInstance().create(path,data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }
    public void setData(String path,String data) throws Exception {
        getInstance().setData(path,data.getBytes(),-1);
    }
    public  void logStat(String prefix ,Stat stat){
        StringBuilder sb = new StringBuilder();
        sb.append("stat.").append("ctime:").append(stat.getCtime()).append(",");
        sb.append("stat.").append("czxid:").append(stat.getCzxid()).append(",");
        sb.append("stat.").append("mtime:").append(stat.getMtime()).append(",");
        sb.append("stat.").append("mzxid:").append(stat.getMzxid()).append(",");
        sb.append("stat.").append("pzxid:").append(stat.getPzxid()).append(",");
        sb.append("stat.").append("version:").append(stat.getVersion()).append(",");
        sb.append("stat.").append("aversion:").append(stat.getAversion()).append(",");
        sb.append("stat.").append("cversion:").append(stat.getCversion()).append(",");
        sb.append("stat.").append("ephemeralOwner:").append(stat.getEphemeralOwner()).append(",");
        sb.append("stat.").append("numChildren:").append(stat.getNumChildren()).append(",");
        sb.append("stat.").append("dataLength:").append(stat.getDataLength()).append(",");
        logger.info(prefix +sb.toString());
    }
}
